package com.yuantu.judiciary.serviceimpl;

import cn.hutool.core.util.URLUtil;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.alipay.easysdk.payment.wap.models.AlipayTradeWapPayResponse;
import com.google.gson.Gson;
import com.yuantu.judiciary.model.dto.AddOrderDTO;
import com.yuantu.judiciary.service.IApiWapAliPayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.LinkedHashMap;

/**
 * APP支付宝支付
 *
 * @author syw
 * @since 2023-09-13
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class ApiWapAliPayServiceImpl implements IApiWapAliPayService {

    private static final Gson GSON = new Gson();
    public static Config open_config;
    public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi/7rUBi4mm2rHzSW0BLey52A69zvbXiE7gz0bvqSKKJSSpLdvBZxhseQBSuUoaOSNzmna5ov1uu0pYC1vWGHsf7YjzcrAl8aYBL+wpVAsjij+fLTeftYleVZZPjIZfGtrggDuO3L4vVrmyszOqRFS9063jy4xnfYsBwXJjmaw2vmXx6BFE+WKAmytgcopk44Jt9HZqezRtV0HcuMnBYfXW1s/9/blqNpphzpk8tWBeb9/kE0gZ2+SkLqU2Gpnn/ImeOWRs5yDKYAOYDec8AAABPGo6F3MRNAX2OSkhce1lnZV9VQvwiotbg5Az8IftwYWVyTXPqOfv/++kj5psyPnQIDAQAB";


    //    public static final String QUIT_URL = "http://47.100.124.208:8908/";
    public static final String QUIT_URL = "https://admin.njxnet.com/pay/";
    // public static final String RETURN_URL = "https://admin.njxnet.com/pay/result";
    public static String RETURN_URL = "https://admin.njxnet.com/vipPay/#/pages/view/successPay?payInfoType=";

    public static Config getOptions() {
        if (open_config == null) {
            Config config = new Config();
            config.protocol = "https";
            config.gatewayHost = "openapi.alipay.com";
            config.signType = "RSA2";
            config.appId = "2021004103655111";
            config.merchantPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCTHb+LMi7v7Et7tGWcV3UFRIk/BO2zE/sZsbrtBwzDgNECRI5AT/VZfzWfLFdFp3t43EWOZkUWZN7BK+zp4hw625FpWbintwBBSqiVkN0QiAG1noZqst+Uzkr4IK987VFz4QVsitJUXYKHQmV5qTyfOuxLsn1Fr80kDqJEGBCVEsLQ5eWxVmk/tk9yzoAEkRgXcD+qsPbi5FqkzDBHDAxwQQAAkUVYp+qqPG5DmEMI/bJPYrFePCHDflMdz52b50nzvbF8vmoP89nKOxrWM8Po0cfnZ3zR/RCemJhBOS5gWEwyI8uWYLK0yoUEf5qvytZLvwQumrEeCErevsS7BHI3AgMBAAECggEBAIwKaFgniBipFV2HZqZBdkpyaDdOCLtMDN3zml2hNVwxFkSTX9oGgyYTesavXdAXUujEvY2E+sULdiPqHVax/29jrXLcjnNQN3TvjbT6NgVTglURtyCAb2ZmTWUPMB26hqvJCvG83+ShMuxwnsoF+IgWffK80JTyeVOWfo5VXguYYqyi5n66g0mR+ybEiZAIHej4SWFr2wpvULSPYnu/JRfcpv0flBmcuo+VRDX2Rtqtvu4427aPYnuQyxP7TekNpu8uH1/dU/SHY+9sseadq/+2Jo2miD3j6NXJs5ahpzal94Si4g2/Ke8gvdXzxX3eZqNwfXOISKMkAq29LPx3zvkCgYEA0gVi24tQaanG/LP81uV0ulteYK3nO30vS9+Bkutd5XANSxVJyn5zEuQbOME4WjG1mOC0PEhljLhHg4NaBq6FR0MiTEDkBCbfZTStN90Ft4Jfs6hyjK4umw5ff+6HigT0N+b8Fb00XRkch0w1wHVKxzeBP/iPdvFeaiWSJ2oqBz0CgYEAs1LdeSBgfWRZveLSGjq9x5CarHx7OJMtX4uj64nWqtf/FmZazGnr8lny0sXW0JS4NswoOOevZ8pA9u/S7N3Q1tklUEGqOznWG7bgaF2/Ud8ovlKPISBWnsn0JDne3BPvYLHyia3iSYJ5DjFaYTZRs/9QCTETVto5hfp7ngCploMCgYEAvZT9Gv9UFD2ckUqMBxRT3VFTDWSN4eZsBkp4tb3fIZiXd1p9JNwmVjww0negvdI3ggv8xpn3iSJj87RjVLq/NofEcx70dUb9y2bUoiPS4EdAynVZCeLF0VQVIu+XzCASsE/C6IDFvvBHD17c+qEmYlSZSLzADHdvadQGbavoymUCgYAf/p/vVZyBot70Jz0PWv2zVpSSQ9+EV5YX3wVPKBe6AbHMoFSA9kEXy36sponOS0qW1FQ02vmLziVLKbz7cBQr0TB8IksqKAaQiU9+r4NMK0HMu1Q4N9ncmPHLaNvfblseaIF6mSCvtuy8YIfcomFveRUhnrTxoRv0UJ2vsjSP2wKBgEgMBm2srYFRgpFsB5KeXNgpcLlswLczJf8EVPt5c6k1uwDw+lpK9Kk25dMO/fnKa61FXA17gsc+dGu+p+ppyYCTX6oYQmB11yx7f/pOpFDk2IEclmYPMf2V9aT10LdD6p5GDCrfVrPku7dFWAtAzl4wJrF6cSLlHl4ZI1U1cF/a";
            config.alipayPublicKey = PUBLIC_KEY;
            //可设置异步通知接收服务地址（可选）
//            config.notifyUrl = "https://cxb.learncoder.com:8901/api/order/notify/app/ali/wap";
            config.notifyUrl = "https://admin.njxnet.com:8901/api/order/notify/app/ali/wap";
            //可设置AES密钥，调用AES加解密相关接口时需要（可选）
            config.encryptKey = "lR6rEv1+k29mXJG0ISbRfQ==";
            return config;
        } else {
            return open_config;
        }
    }

    @Override
    public String addOrder(AddOrderDTO data) {
        Factory.setOptions(getOptions());
        try {
            RETURN_URL = RETURN_URL + data.getType();
            AlipayTradeWapPayResponse response = Factory.Payment.Wap().pay(data.getName(), data.getTradeNo(),
                    data.getTotalPrice().toString(), QUIT_URL, RETURN_URL);
            if (ResponseChecker.success(response)) {
                return response.getBody();
            } else {
                log.info("APP支付宝支付-创建订单失败，返回值：{}", GSON.toJson(response));
            }
        } catch (Exception e) {
            log.error("APP支付宝支付-创建订单异常，原因：" + e.getMessage(), e);
        }
        return "";
    }

    @Override
    public String addTimeOrder(AddOrderDTO data) {
        Config options = getOptions();
        options.notifyUrl = "https://admin.njxnet.com:8901/api/order/notify/app/ali/time/wap";
        Factory.setOptions(options);
        try {
            AlipayTradeWapPayResponse response = Factory.Payment.Wap().pay(data.getName(), data.getTradeNo(),
                    data.getTotalPrice().toString(), QUIT_URL, null);
            if (ResponseChecker.success(response)) {
                return response.getBody();
            } else {
                log.info("定时监控支付宝支付-创建订单失败，返回值：{}", GSON.toJson(response));
            }
        } catch (Exception e) {
            log.error("定时监控支付宝支付-创建订单异常，原因：" + e.getMessage(), e);
        }
        return null;
    }

    @Override
    public LinkedHashMap<String, String> callOrder(HttpServletRequest request) {
        Factory.setOptions(getOptions());
        try {
            BufferedReader br = request.getReader();
            String str;
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            //回调的待验签字符串
            String params = URLUtil.decode(sb.toString(), "utf-8");
            //对待签名字符串数据通过&进行拆分
            String[] temp = params.split("&");
            LinkedHashMap<String, String> map = new LinkedHashMap<>();
            //把拆分数据放在map集合内
            for (int i = 0; i < temp.length; i++) {
                //通过"="号分割成2个数据
                String[] arr = temp[i].split("=", 2);
                //再开辟一个数组用来接收分割后的数据
                String[] tempAagin = new String[arr.length];
                for (int j = 0; j < arr.length; j++) {
                    tempAagin[j] = arr[j];
                }
                map.put(tempAagin[0], tempAagin[1]);
            }
            log.info("支付回调构造参数: {}", map);
            String outTradeNo = map.get("out_trade_no");
            String tradeStatus = map.get("trade_status");
            log.info("APP支付宝支付-回调信息-订单：{}，交易状态：{}", outTradeNo, tradeStatus);
            boolean verifyNotify = AlipaySignature.rsaCheckV1(map, PUBLIC_KEY, "utf-8", "RSA2");
            log.info("APP支付宝支付-验签结果: {}", verifyNotify);

            if (Boolean.TRUE.equals(verifyNotify)) {
                return map;
            } else {
                log.info("APP支付宝支付-验签失败，回调参数: {}", params);
            }
        } catch (Exception e) {
            log.error("APP支付宝支付-验签异常，原因：" + e.getMessage(), e);
        }

        return null;
    }

}
